import os,sys
import struct
import fcntl
import termios
import pexpect
import xerox

def clipboard(string):
    if os.system("which xclip > /dev/null 2>&1 ") != 0:
        return
        
    xerox.copy(string)

def getwinsize():
    """This returns the window size of the child tty.
    The return value is a tuple of (rows, cols).
    """
    if 'TIOCGWINSZ' in dir(termios):
        TIOCGWINSZ = termios.TIOCGWINSZ
    else:
        TIOCGWINSZ = 1074295912L # Assume
    s = struct.pack('HHHH', 0, 0, 0, 0)
    x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s)
    return struct.unpack('HHHH', x)[0:2]

def expect(cmd, passwd, match):
    child = pexpect.spawn(cmd)
    try:
        out = child.expect(['password:', 'continue connecting (yes/no)?'])
        if out == 0 :
            child.sendline(passwd)
        elif out == 1:
            child.sendline('yes')

        winsize = getwinsize();
        child.setwinsize(winsize[0], winsize[1])
        child.interact()
    except:
        child.close()
    else:
        if child.isalive():
            child.close()


def ssh(host, user, passwd, port="22", key=None, show=False):
    args = {"passwd": passwd, "user": user,
            "host": host, "port": port, "key": ""}

    if key:
        args["key"] = "-i " + key

    cmd = r"zssh -p %(port)s %(key)s %(user)s@%(host)s" % args

    if show:
        print cmd
        return

    if user!="root":
        print "root passwd: " + (passwd if passwd else "no root passwd!")

    if passwd and not key:
        expect(cmd, args["passwd"], 'password:')
    else:
        os.system(cmd)

def rdp(host,user,passwd,port,show=False):
    args = {"passwd": passwd, "user": user, "host": host, "port": port}
    cmd = r"rdesktop %(host)s:%(port)s -a 24 -K -z -b -P -x 0x80 -k en-us -clipboard \
    -u %(user)s -p'%(passwd)s' -g 1440x900 -r sound:off -r disk:share=/home/kong/RAM/ >> /dev/null 2>&1 &" % args

    if show:
        print cmd
        return

    os.system(cmd)
